package com.example.mainexam2022110341

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.icu.util.Calendar
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.gridlayout.widget.GridLayout

class YearActivity : AppCompatActivity() {

    private val months = listOf(
        "一月" to 31,
        "二月" to 28, // 二月的天数稍后动态处理
        "三月" to 31,
        "四月" to 30,
        "五月" to 31,
        "六月" to 30,
        "七月" to 31,
        "八月" to 31,
        "九月" to 30,
        "十月" to 31,
        "十一月" to 30,
        "十二月" to 31
    )

    private lateinit var mainLayout: LinearLayout
    private val currentYear = Calendar.getInstance().get(Calendar.YEAR)
    private var earliestYear = 0
    private var maxYear = 0
    private var currentMonth = 0
    private var currentDay = 0
    private var isfirstRun = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DateEventManager.initialize(this)

        // 设置当前年份、月份和日期
        val calendar = Calendar.getInstance()
        currentMonth = calendar.get(Calendar.MONTH) + 1 // Calendar.MONTH 从0开始
        currentDay = calendar.get(Calendar.DAY_OF_MONTH)

        val scrollView = ScrollView(this)
        mainLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(16, 16, 16, 16)
        }

        // 获取传递过来的数据
        earliestYear = intent.getIntExtra("earliestYear", currentYear)
        maxYear = intent.getIntExtra("maxYear", currentYear + 2)
        var scrollPosition = intent.getIntExtra("scrollPosition", 0)
        isfirstRun = intent.getBooleanExtra("isfirstRun", true)

        // 初始化加载内容
        for (year in earliestYear..maxYear) {
            addYearView(year, scrollView)
        }

        scrollView.addView(mainLayout)
        setContentView(scrollView)

        scrollView.post {
            scrollView.scrollTo(0, scrollPosition)
        }

        // 设置滚动监听器
        scrollView.viewTreeObserver.addOnScrollChangedListener {
            val view = scrollView.getChildAt(scrollView.childCount - 1) as View
            val diff = view.bottom - (scrollView.height + scrollView.scrollY)

            if (diff == 0) {
                // 滑动到底部，加载下一年
                maxYear++
                addYearView(maxYear, scrollView)
            }

            if (scrollView.scrollY == 0) {
                // 滑动到顶部，加载前一年
                val previousScrollY = scrollView.scrollY
                earliestYear--
                addYearView(earliestYear, scrollView, atTop = true)
                scrollView.post {
                    scrollView.scrollTo(0, previousScrollY + mainLayout.getChildAt(0).height + mainLayout.getChildAt(1).height)
                }
            }
        }

        // 检查是否有今日的日程
        if(checkTodayEvents()&&isfirstRun) {
            requestNotificationPermission()
        }

    }


    private fun addYearView(year: Int, scrollView: ScrollView, atTop: Boolean = false) {
        val yearTextView = TextView(this).apply {
            text = "${year}年"
            textSize = 24f
            setTypeface(null, Typeface.BOLD)
            setPadding(0, 16, 0, 16)
            if (year == currentYear) {
                setTextColor(Color.RED) //当前年份设置为红色
            }
        }

        val gridLayout = GridLayout(this).apply {
            columnCount = 2 //2列
            setPadding(0, 0, 0, 32)
        }

        setupYearGrid(gridLayout, year, scrollView)

        if (atTop) {
            mainLayout.addView(gridLayout, 0)
            mainLayout.addView(yearTextView, 0)
        } else {
            mainLayout.addView(yearTextView)
            mainLayout.addView(gridLayout)
        }
    }

    private fun setupYearGrid(gridLayout: GridLayout, year: Int, scrollView: ScrollView) {
        gridLayout.removeAllViews() // 清空之前的视图
        gridLayout.columnCount = 2 // 设置列数

        for ((index, month) in months.withIndex()) {
            val actualDays = if (month.first == "二月") {
                if (isLeapYear(year)) 29 else 28
            } else {
                month.second
            }

            val cardView = CardView(this).apply {
                layoutParams = GridLayout.LayoutParams().apply {
                    width = 0
                    setBackgroundColor(Color.WHITE)
                    height = GridLayout.LayoutParams.WRAP_CONTENT
                    setMargins(8, 8, 8, 8)
                    columnSpec = GridLayout.spec(index % gridLayout.columnCount, 1f) // 列位置和跨度
                    rowSpec = GridLayout.spec(index / gridLayout.columnCount, 1f) // 行位置和跨度
                }
                radius = 8f
                cardElevation = 4f
            }
            val linearLayout = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.TOP // 确保内容从顶部开始对齐
                setPadding(16, 16, 16, 16)
            }
            val monthTitle = TextView(this).apply {
                text = month.first
                textSize = 18f
                setTypeface(null, Typeface.BOLD)
                setPadding(0, 8, 0, 8)
                if (year == currentYear && index + 1 == currentMonth) {
                    setTextColor(Color.RED) // 当前月份设置为红色
                }
            }
            val datesLayout = GridLayout(this).apply {
                columnCount = 7
                setPadding(0, 8, 0, 8)
            }

            // 获取每个月的一号是星期几
            val calendar = Calendar.getInstance()
            calendar.set(year, index, 1)
            val firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1 // Calendar.DAY_OF_WEEK 从1开始，周日是1

            // 添加空白占位符
            for (i in 0 until firstDayOfWeek) {
                val emptyView = TextView(this).apply {
                    text = ""
                }
                datesLayout.addView(emptyView)
            }

            for (day in 1..actualDays) {
                val dayView = TextView(this).apply {
                    text = day.toString()
                    textSize = 15f
                    setPadding(8, 8, 8, 8)
                    gravity = Gravity.CENTER
                    if (year == currentYear && index + 1 == currentMonth && day == currentDay) {
                        setTextColor(Color.RED) // 当前日期设置为红色
                        textSize = 21f
                        setTypeface(null, Typeface.BOLD)
                    }
                }
                datesLayout.addView(dayView)
            }
            linearLayout.addView(monthTitle)
            linearLayout.addView(datesLayout)
            cardView.addView(linearLayout)
            gridLayout.addView(cardView)
            // 设置 CardView 点击颜色变化
            cardView.setOnTouchListener { v, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        v.setBackgroundColor(Color.LTGRAY) // 按下时改变背景颜色
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        v.setBackgroundColor(Color.WHITE) // 松开时恢复背景颜色
                    }
                }
                false
            }
            cardView.setOnClickListener {
                val scrollPosition = scrollView.scrollY
                val intent = Intent(this, MonthActivity::class.java)
                intent.putExtra("month", index)
                intent.putExtra("year", year)
                intent.putExtra("earliestYear", earliestYear)
                intent.putExtra("maxYear", maxYear)
                intent.putExtra("scrollPosition", scrollPosition)
                startActivity(intent)
            }
        }
    }

    private fun isLeapYear(year: Int): Boolean {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
    }

    private fun checkTodayEvents(): Boolean {
        val calendar = Calendar.getInstance()
        val year = calendar.get(Calendar.YEAR).toString()
        val month = (calendar.get(Calendar.MONTH) + 1).toString()
        val day = calendar.get(Calendar.DAY_OF_MONTH).toString()
        val events = DateEventManager.getEvents(year, month, day)
        return events != null
    }

    private fun sendNotification() {
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId = "day_events_channel"
        val channelName = "Day Events"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }
        val intent = Intent(this, DayEventsActivity::class.java)
        intent.putExtra("year", currentYear)
        intent.putExtra("month", currentMonth)
        intent.putExtra("day", currentDay)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("今日日程提醒")
            .setContentText("您有今日的日程安排，请查看。")
            .setSmallIcon(R.drawable.ic_notification_foreground)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()
        notificationManager.notify(1, notification)
    }

    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            when {
                ContextCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED -> {
                    // 权限已授予，发送通知
                    sendNotification()
                }
                shouldShowRequestPermissionRationale(android.Manifest.permission.POST_NOTIFICATIONS) -> {
                    // 显示权限请求理由
                    Log.d("MainActivity", "需要通知权限")
                }
                else -> {
                    // 请求权限
                    requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 1)
                }
            }
        } else {
            // 低于 Android 13，直接发送通知
            sendNotification()
        }
    }
}